<template>
  <view class="app">
    <view class="flex mt-10 justify-center">
      <div class="font-size-30rpx px-4 py-2 mr-2 rounded-1 bg-blue-500 color-white" @click="login()">
        登录
      </div>
      <div class="font-size-30rpx px-4 py-2 mr-2 rounded-1 bg-blue-500 color-white" @click="request(0)">
        请求接口
      </div>
      <div class="font-size-30rpx px-4 py-2 mr-2 rounded-1 bg-blue-500 color-white" @click="refresh()">
        刷新token
      </div>
      <div class="font-size-30rpx px-4 py-2 rounded-1 bg-blue-500 color-white" @click="stop()">停止</div>
    </view>
  </view>
</template>

<script lang="ts" setup>
  import { h5OauthByPassword, blank } from '@/api/auth';
  import { refreshToken } from '@/api/reauth';
  import { useFansStore } from '@/store/fans';

  const fansStore = useFansStore();

  const login = () => {
    h5OauthByPassword('13580446805', '123456').then((res) => {
      fansStore.fansinfo = res.data;
      console.log('登录成功');
      request(1);
    });
  };

  let timer: any;
  const request = (loop: number) => {
    if (loop == 0) {
      blank()
        .then((res) => {
          console.log('访问成功，刷新token次数：', res.data);
        })
        .catch((err) => {
          if (err.code == 401) {
            console.log('授权失败');
            clearInterval(timer);
          }
        });
    } else {
      timer = setInterval(() => {
        blank()
          .then((res) => {
            console.log('访问成功，刷新token次数：', res.data);
          })
          .catch((err) => {
            if (err.code == 401) {
              console.log('授权失败');
              clearInterval(timer);
            }
          });
      }, 1000);
    }
  };
  const refresh = () => {
    refreshToken().then((res) => {
      console.log('新token');
      fansStore.fansinfo.token = res.data.token;
      if (res.data.refresh_token) {
        console.log('新refresh_token');
        fansStore.fansinfo.refresh_token = res.data.refresh_token;
      }
    });
  };

  const stop = () => {
    clearInterval(timer);
  };
</script>
